package com.hzzftech.watchdog.busi.core.util;

import com.hzzftech.watchdog.common.utils.uuid.UUID;
import org.apache.commons.codec.binary.Base64;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.SwingGC;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.JobPainter;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPainter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class KettleImgUtil {
    public static Logger logger = LoggerFactory.getLogger(KettleImgUtil.class);

    public static String getJobImg(JobMeta meta, String filePath) throws KettleException, IOException {
        float f = 1.0f;
        Point max = meta.getMaximum();
        max.multiply(f);

        SwingGC swingGC = new SwingGC(null, max, 32, 0, 0);
        JobPainter jobPainter = new JobPainter(swingGC, meta, max, null,null,null,null,null,
                new ArrayList<>(), new ArrayList<>(), 32,1,0,0,true,"Arial",10);
        jobPainter.setMagnification(f);
        jobPainter.drawJob();;

        BufferedImage image = (BufferedImage) swingGC.getImage();
        return writeFileImg(image, meta.getName(), filePath);
    }

    public static String getTransImg(TransMeta meta, String filePath) throws KettleException, IOException {
        float f = 1.0f;
        Point max = meta.getMaximum();
        max.multiply(f);

        SwingGC swingGC = new SwingGC(null, max, 32, 0, 0);
        TransPainter transPainter = new TransPainter(swingGC, meta, max, null,null,null,null,null,
                new ArrayList<>(), new ArrayList<>(), 32,1,0,0,true,"Arial",10);
        transPainter.setMagnification(f);
        transPainter.buildTransformationImage();
        BufferedImage image = (BufferedImage) swingGC.getImage();
        return writeFileImg(image, meta.getName(), filePath);
    }

    private static String writeFileImg(BufferedImage image, String name, String filePath) throws IOException {
        StringBuffer filebuffer = new StringBuffer();
        filebuffer.append(name).append("_").append(UUID.randomUUID()).append(".png");
        File logF = new File(filePath);
        if (!logF.exists()) {
            logF.mkdirs();
        }
        FileOutputStream outputStream = new FileOutputStream(new File(logF, filebuffer.toString()));
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
        return logF.getAbsolutePath()+File.separator+filebuffer;
    }

    public static String getImg(String httpUrl, String header, String filePath) {
        URL url = null;
        BufferedInputStream in = null;
        FileOutputStream out = null;

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            logger.info("获取Kettle执行图片");
            String fileName = httpUrl.substring(httpUrl.lastIndexOf("/")+2)
                    .replaceAll("=","").replaceAll("&", "")+".png";
            url = new URL(httpUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization","Basic"+ Base64.encodeBase64String(header.getBytes()));

            in = new BufferedInputStream(urlConnection.getInputStream());
            out = new FileOutputStream(filePath + "/" + fileName);
            int t;
            while ((t=in.read())!=-1) {
                out.write(t);
            }
            logger.info("图片获取成功");
            return fileName;
        } catch (Exception e) {
            logger.error("图片获取失败", e);
            return null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("关闭流失败", e);
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("关闭流失败", e);
                }
            }
        }
    }
}
